<template>
    <basic-container>
        <avue-crud :option="option"
                   :table-loading="loading"
                   :data="data"
                   v-model:page="page"
                   v-model:search="search"
                   :permission="permissionList"
                   :before-open="beforeOpen"
                   v-model="form"
                   ref="crud"
                   @sort-change="sortChange"
                   @search-change="searchChange"
                   @search-reset="searchReset"
                   @selection-change="selectionChange"
                   @current-change="currentChange"
                   @size-change="sizeChange"
                   @refresh-change="refreshChange"
                   :summary-method="summaryMethod"
                   >
            <template #menu-left>
                <el-button
                        type="warning"
                        icon="el-icon-download"
                        @click="handleExport"
                >导出
                </el-button>
                <el-button
                        type="success"
                        icon="Check"
                        @click="handleCheck"
                        v-if="permission.bill_check_audit"
                >过账
                </el-button>
                <el-button
                        type="danger"
                        icon="Close"
                        @click="handleUnCheck"
                        v-if="permission.bill_check_reject"
                >反过账
                </el-button>
            </template>
            <template #stockDate-search="{ disabled, size }">
                <!--<div style="display: flex;flex-direction: start;">-->
                    <!--<el-select v-model="query.stockDateRule" placeholder="比较" filterable clearable>-->
                        <!--<el-option label="" value=""></el-option>-->
                        <!--<el-option value=">" label="大于">大于</el-option>-->
                        <!--<el-option value=">=" label="大于等于">大于等于</el-option>-->
                        <!--<el-option value="=" label="等于">等于</el-option>-->
                        <!--<el-option value="!=" label="不等于">不等于</el-option>-->
                        <!--<el-option value="<=" label="小于等于">小于等于</el-option>-->
                        <!--<el-option value="<" label="小于">小于</el-option>-->
                    <!--</el-select>-->
                    <!--<el-date-picker-->
                            <!--size="default"-->
                            <!--v-model="query.stockDateSearch"-->
                            <!--type="date"-->
                            <!--:format="dateFormat"-->
                            <!--:value-format="dateFormat"-->
                            <!--:unlink-panels="true"-->
                            <!--clearable-->
                            <!--placeholder="入仓日期"-->
                            <!--:picker-options="pickerOptions"-->
                    <!--&gt;-->
                    <!--</el-date-picker>-->
                <!--</div>-->
                <el-date-picker
                        size="default"
                        style="width:94%"
                        v-model="this.stockDateRange"
                        type="daterange"
                        :format="dateFormat"
                        :value-format="dateFormat"
                        unlink-panels
                        start-placeholder="Start Date"
                        end-placeholder="End Date"
                        clearable
                        placeholder="入仓日期"
                        @change="handleStockDateChange"
                        :picker-options="pickerOptions"
                >
                </el-date-picker>
            </template>
        </avue-crud>
    </basic-container>
</template>

<script>
    import {purBillCheckPage} from "@/api/anwise/stock/stock_in_item";
    import {changeBillStatus} from "@/api/anwise/stock/stock_in_main";
    import {findListByOwner} from "@/api/anwise/supplier";
    import {mapGetters} from "vuex";
    import { getToken } from '@/utils/auth';
    import { exportBlobPost } from '@/api/common';
    import { downloadXls } from '@/utils/util';
    import NProgress from 'nprogress';
    import 'nprogress/nprogress.css';
    import {generateQCSign} from "@/api/common";

    export default {
        data() {
            return {
                form: {},
                query: {},
                search:{},
                fileName:'',
                stockDateRange:[],
                loading: true,
                page: {
                    pageSize: 20,
                    currentPage: 1,
                    total: 0
                },
                selectionList: [],
                dateFormat: 'YYYY-MM-DD',
                pickerOptions: {},
                option: {
                    height:'auto',
                    calcHeight: 30,
                    tip: false,
                    searchShow: true,
                    searchMenuSpan: 6,
                    border: true,
                    index: true,
                    selection: false,
                    reserveSelection:true,
                    labelWidth: 150,
                    indexWidth:100,
                    menuWidth: 180,
                    addBtn: false,
                    editBtn: false,
                    viewBtn: false,
                    delBtn: false,
                    stripe: true,
                    searchIndex: 3,
                    searchIcon: false,
                    searchLabelWidth:120,
                    searchEnter:true,
                    menu:false,
                    showSummary: true,
                    column: [
                        {
                            label: "采购商",
                            prop: "fromDept",
                            type: "select",
                            filterable: true,
                            // virtualize:true,
                            search:true,
                            hide:true,
                            dicData:[],
                            props: {
                                label: 'supName',
                                value: 'deptId',
                            },
                            dataType: 'string',
                            rules: [{
                                required: true,
                                message: "请选择采购商",
                                trigger: "blur"
                            }],
                            change:(data)=>{console.log(data);if (data.item) {this.fileName=data.item.label}},
                          // change:(data)=>{console.log(data);if (data.item) {this.fileName=data.item.supName}},
                        },
                        {
                            label: "入仓日期",
                            prop: "stockDate",
                            type: "date",
                            fixed: true,
                            search: true,
                            overHidden: true,
                            sortable: true,
                            valueFormat: 'YYYY-MM-DD',
                            format:'YYYY-MM-DD',
                            width:140,
                            rules: [{
                                required: true,
                                message: "请输入入仓日期",
                                trigger: "blur"
                            }],
                        },
                        {
                            label: "入仓单号",
                            prop: "idNo",
                            type: "input",
                            fixed: true,
                            overHidden: true,
                            sortable: true,
                            width:180,
                            rules: [{
                                required: true,
                                message: "请输入入仓单号",
                                trigger: "blur"
                            }],
                        },
                        {
                            label: "送货单号",
                            prop: "deliNo",
                            type: "input",
                            overHidden: true,
                            sortable: true,
                            width:140,
                        },
                        {
                            label: "采购单号",
                            prop: "aboutNo",
                            type: "input",
                            overHidden: true,
                            sortable: true,
                            width:120,
                        },
                        {
                            label: "采购类别",
                            prop: "purchaseType",
                            type: "select",
                            overHidden: true,
                            sortable: true,
                            filterable:true,
                            clearable:false,
                            value:'正常',
                            width:120,
                            dicUrl: '/api/blade-system/dict-biz/dictionary?code=purchase_type',
                            props: {
                                label: 'dictValue',
                                value: 'dictKey',
                            },
                            dataType: 'string',
                            rules: [{
                                required: false,
                                message: "请输入采购类别",
                                trigger: "blur"
                            }],
                        },
                        {
                            label: "是否已对账",
                            prop: "billCheck",
                            type: "input",
                            overHidden: true,
                            sortable: true,
                            width:140,
                        },
                        {
                            label: "物料编号",
                            prop: "materialNo",
                            type: "input",
                            overHidden: true,
                            sortable: true,
                            width:180,
                        },
                        {
                            label: "客户条码",
                            prop: "barCode",
                            type: "input",
                            overHidden: true,
                            sortable: true,
                            width:180,
                        },
                        {
                            label: "物料名称",
                            prop: "materialName",
                            type: "input",
                            overHidden: true,
                            sortable: true,
                            width:180,
                        },
                        {
                            label: "规格",
                            prop: "specification",
                            type: "input",
                            overHidden: true,
                            sortable: true,
                            width:180,
                        },
                        {
                            label: "单位",
                            prop: "unit",
                            type: "input",
                            overHidden: true,
                            sortable: true,
                            width:180,
                        },
                        {
                            label: "数量",
                            prop: "num",
                            type: "input",
                            overHidden: true,
                            sortable: true,
                            width:180,
                        },
                        {
                            label: "单价",
                            prop: "price",
                            type: "input",
                            overHidden: true,
                            sortable: true,
                            width:180,
                        },
                        {
                            label: "金额",
                            prop: "totalPrice",
                            type: "input",
                            overHidden: true,
                            sortable: 'custom',
                            width:180,
                            // formatter:(row,value,label)=>{
                            //     if (row.orderPrice && row.num) {
                            //         return (row.num * row.orderPrice).toFixed(2);
                            //     } else {
                            //         return 0
                            //     }
                            // },
                        },
                        {
                            label: "备注",
                            prop: "remark",
                            type: "input",
                            overHidden: true,
                            sortable: true,
                            width:180,
                        },
                    ]
                },
                data: []
            };
        },
        computed: {
            ...mapGetters(["userInfo","permission"]),
            permissionList() {
                return {
                    checkPriceBtn: this.validData(this.permission.stock_in_check_price, false),
                    viewBtn: this.validData(this.permission.stock_in_details_view, false),
                };
            },
        },
        mounted() {
            this.loading = false;
            this.init();
        },
        methods: {
            handleCheck() {
                if (!this.query.stockDateStart || !this.query.stockDateEnd || !this.query.fromDept|| this.query.stockDateEnd=='' || this.query.stockDateStart=='') {
                    this.loading = false;
                    this.$message({
                        type: "error",
                        message: "请选择采购商并输入入仓日期范围！"
                    });
                    return;
                }
                changeBillStatus(this.query,1,1).then(res=> {
                    if (res.data.success) {
                        this.$message({
                            type: "success",
                            message: res.data.msg || "对账成功！"
                        });
                        this.onLoad(this.page);
                    }else {
                        this.$message({
                            type: "error",
                            message: res.data.msg
                        });
                    }
                })
            },
            handleUnCheck() {
                if (!this.query.stockDateStart || !this.query.stockDateEnd || !this.query.fromDept|| this.query.stockDateEnd=='' || this.query.stockDateStart=='') {
                    this.loading = false;
                    this.$message({
                        type: "error",
                        message: "请选择采购商并输入入仓日期范围！"
                    });
                    return;
                }
                changeBillStatus(this.query,1,0).then(res=> {
                    if (res.data.success) {
                        this.$message({
                            type: "success",
                            message: res.data.msg || "反对账成功！"
                        });
                        this.onLoad(this.page);
                    }else {
                        this.$message({
                            type: "error",
                            message: res.data.msg
                        });
                    }
                })
            },
            summaryMethod ({ columns, data }) {
                const sums = [];
                if (columns.length > 0) {
                    sums[0] = '合计：';
                    columns.forEach((column, index) => {
                        let prop = column.property
                        if (['num','totalPrice'].includes(prop)) {
                            let values = this.data.map(item => Number(item[prop] || 0));
                            let all = values.length !== 0 ? sums[index] = values.reduce((a, b) => {
                                return a + b;
                            }) : 0
                            if (prop == 'num' ) {
                                sums[index] = all.toFixed(0)
                            } else if (prop == 'totalPrice') {
                                sums[index] = this.$toFixed(all,2)
                            }
                        }
                    });
                }
                return sums;
            },
            init(){

                findListByOwner(2,this.userInfo.dept_id).then(res => {
                    if (res.data.success) {
                        this.findObject(this.option.column, 'fromDept').dicData=res.data.data;
                    }
                })
            },
            handleExport(){
                if (!this.query.stockDateStart || !this.query.stockDateEnd || !this.query.fromDept|| this.query.stockDateEnd=='' || this.query.stockDateStart=='') {
                    this.loading = false;
                    this.$message({
                        type: "error",
                        message: "请选择采购商并输入入仓日期范围！"
                    });
                    return;
                }
                NProgress.start();
                exportBlobPost(
                    `/blade-anwise/stock/stock_in_item/exportPurBillCheck?${this.website.tokenHeader
                    }=${getToken()}`, this.query
                ).then(res => {
                    downloadXls(res.data, this.fileName+`对账单${this.$dayjs().format('YYYYMMDDHHmmss')}.xlsx`);
                    NProgress.done();
                });
            },
            beforeOpen(done, type) {
                if (["edit", "view"].includes(type)) {
                    getDetail(this.form.id).then(res => {
                        this.form = res.data.data;
                    });
                }
                done();
            },
            searchReset() {
                this.query = {};
                this.stockDateRange = [];
                this.search.stockDateStart = '';
                this.search.stockDateEnd = '';
                // this.onLoad(this.page);
                this.data = [];
                this.page.total = 0;
            },
            sortChange(val) {
                console.log(val)
                this.sort = {
                    prop: val.prop,
                    order: val.order
                };
                let order = "";
                if (this.sort.prop && this.sort.order) {
                    if (this.sort.order === "descending") {
                        order = `${this.sort.prop} desc`
                    } else {
                        order = `${this.sort.prop} asc`
                    }
                }
                this.query.orderBy = order;
                this.onLoad(this.page);
            },
            searchChange(params, done) {
                this.query = params;
                // Object.assign(this.query, params)
                this.page.currentPage = 1
                this.onLoad(this.page, params);
                done();
            },
            selectionChange(list) {
                this.selectionList = list;
            },
            selectionClear() {
                this.selectionList = [];
                this.$refs.crud.toggleSelection();
            },
            currentChange(currentPage){
                this.page.currentPage = currentPage;
                this.onLoad(this.page, this.query);
            },
            sizeChange(pageSize){
                this.page.pageSize = pageSize;
                this.onLoad(this.page, this.query);
            },
            refreshChange() {
                this.onLoad(this.page, this.query);
            },
            onLoad(page, params = {}) {
                this.loading = true;
                let filter = Object.assign(params, this.query);
                if (!filter.stockDateStart || !filter.stockDateEnd || !filter.fromDept) {
                    this.loading = false;
                    this.$message({
                        type: "error",
                        message: "请选择采购商并输入入仓日期范围！"
                    });
                    return;
                }
                purBillCheckPage(page.currentPage, page.pageSize, filter).then(res => {
                    const data = res.data.data;
                    this.page.total = data.total;
                    this.data = data.records;
                    this.loading = false;
                    this.selectionClear();
                });
            },

            handleStockDateChange(value) {
                if (value) {
                    this.search.stockDateStart = value[0];
                    this.search.stockDateEnd = value[1];
                } else {
                    this.search.stockDateStart = '';
                    this.search.stockDateEnd = '';
                }
            }
        }
    };
</script>

<style>
</style>
